package dao.Impl;

import dao.organizationDao;
import entity.Organization;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class OrganizationDao implements organizationDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    private static final String SQL_INSERT_ORGANIZATION =
            "INSERT INTO organization (org_parent_id, org_name) VALUES (?, ?)";

    private static final String SQL_FIND_BY_ID =
            "SELECT * FROM organization WHERE org_id = ?";

    private static final String SQL_FIND_ALL =
            "SELECT * FROM organization";

    private static final String SQL_UPDATE_ORGANIZATION =
            "UPDATE organization SET org_parent_id = ?, org_name = ? WHERE org_id = ?";

    private static final String SQL_DELETE_BY_ID =
            "DELETE FROM organization WHERE org_id = ?";

    @Override
    public void create(Organization organization) {
        jdbcTemplate.update(SQL_INSERT_ORGANIZATION,
                organization.getOrgParentId(),
                organization.getOrgName());
    }

    @Override
    public Organization findById(Long orgId) {
        return jdbcTemplate.queryForObject(SQL_FIND_BY_ID, new Object[]{orgId},
                BeanPropertyRowMapper.newInstance(Organization.class));
    }

    @Override
    public List<Organization> findAll() {
        return jdbcTemplate.query(SQL_FIND_ALL,
                BeanPropertyRowMapper.newInstance(Organization.class));
    }

    @Override
    public void update(Organization organization) {
        jdbcTemplate.update(SQL_UPDATE_ORGANIZATION,
                organization.getOrgParentId(),
                organization.getOrgName(),
                organization.getOrgId());
    }

    @Override
    public void deleteById(Long orgId) {
        jdbcTemplate.update(SQL_DELETE_BY_ID, orgId);
    }
}
